package cn.edu.hit.core;

import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;

public class Document extends TreeMap<String, Object> {

    public Document() {
    }

    public Document(Map doc) {
        super(doc);
    }

    public Document(String key, Object value) {
        this.put(key, value);
    }

    public String getString(String key) {
        return Optional.ofNullable(get(key)).map(Object::toString).orElse(null);
//        return get(key).toString();
    }

    public String getString(String key, String defaultValue) {
        return Optional.ofNullable(get(key)).map(Object::toString).orElse(defaultValue);
//        return get(key).toString();
    }

    public Integer getInteger(String key) {
        Object value = get(key);
        if (value instanceof Number)
            return ((Number) value).intValue();
        return Integer.parseInt(value.toString());
    }

    public Long getLong(Object key) {
        Object value = get(key);
        if (value instanceof Number)
            return ((Number) value).longValue();
        return Long.parseLong(value.toString());
    }

    public Double getDouble(Object key) {
        Object value = get(key);
        if (value instanceof Number)
            return ((Number) value).doubleValue();
        return Double.parseDouble(value.toString());
    }

    public String getObjectId(String id) {
        Object oid = get(id);
        if (oid == null) {
            return null;
        }
        if (oid instanceof Map)
            return ((Map) oid).get("$oid").toString();

        return oid.toString();
    }

    public Object get(String key, Object defaultValue) {
        return super.getOrDefault(key, defaultValue);
    }

    public Document pair(String key, Object value) {
        this.put(key, value);
        return this;
    }

}
